package cn.jekun.web.shop.action;

import java.sql.Types;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import cn.jekun.component.base.bean.ErrorMsg;
import cn.jekun.component.base.exceptions.BusinessException;
import cn.jekun.component.base.utils.SqlUtis;
import cn.jekun.component.core.Constants;
import cn.jekun.component.core.bean.gen.ErpOrders;
import cn.jekun.component.core.bean.gen.McMember;
import cn.jekun.component.core.bean.gen.RsMessage;
import cn.jekun.component.core.service.gen.McMemberService;
import cn.jekun.component.shop.service.SendMessageService;
import cn.jekun.web.shop.bean.Message;
import cn.jekun.web.shop.service.PushMessageService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@SuppressWarnings("serial")
public class PushMessageAction extends ShopBaseAction{

	@Resource(name=PushMessageService.BEAN_NAME)
	PushMessageService pushMessageService;
	
	@Resource(name=McMemberService.BEAN_NAME)
	McMemberService mcMemberService;
	
	@Resource(name=SendMessageService.BEAN_NAME)
	SendMessageService sendMessageService;
	
	
	/**
	 * 获取登录者创建的推送消息列表
	 * @return
	 */
	public String queryPushMessageList(){
		
		JSONObject jsonObject=new JSONObject();
		try {
			
			//检测是否拥有 权限
			boolean PUSHMESSAGE = this.coreAuthService.checkRigth(this.getSessionUser().getUserId(), "SHOP_PUSHMESSAGE_MANAGER_PUSHMESSAGE");
			
			//是否出现按钮
			jsonObject.put("PUSHMESSAGE",PUSHMESSAGE) ;
			jsonObject.put("shopSign",this.getSessionUser().getShopName()) ;
			
			
			String shopId=this.getSessionUser().getShopId();
			String beginDate=request.getParameter("beginDate");
			String endDate=request.getParameter("endDate");
			String queryTitle=request.getParameter("title");
			String queryContent=request.getParameter("content");
			
			List<Message> messageList=this.pushMessageService.queryPushMessageList(shopId,beginDate,endDate,queryTitle,queryContent, page);
			
			//获取商家所有会员数量
			Map queryMap=new HashMap();
			queryMap.put(McMember.COL_SHOP_ID, shopId);
			SqlUtis.prepareSql(queryMap, SqlUtis.getSQLRequired(queryMap,McMember.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
			List<McMember> memberList=this.mcMemberService.list(queryMap);
			
			
			JSONArray jsonArray=new JSONArray();
			HashMap<String, Object> hashMap;
			if(messageList.size()>0){
				for (int i = 0; i < messageList.size(); i++) {
					hashMap=new HashMap<String, Object>();
					hashMap.put("title", messageList.get(i).getTitle()==null?"":messageList.get(i).getTitle());
					
					String message = messageList.get(i).getMessage()==null?"":messageList.get(i).getMessage();
					
					int flag=message.indexOf("】");//截取签名
					String sign="";
					String content="";
					if(flag>0){
						sign=message.substring(0, flag+1);//包括"】"
					}
					content=message.substring(flag+1);//不包括"】"
					hashMap.put("sign", sign);
					hashMap.put("content", content);
					hashMap.put("createTime", messageList.get(i).getCreateTime()==null?"":messageList.get(i).getCreateTime());
					hashMap.put("readedNum", messageList.get(i).getReadedSum()==null?"":messageList.get(i).getReadedSum());
					
					jsonArray.add(hashMap);
				
				}
				
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);

				jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");

				jsonObject.put(Constants.Page.PAGE_NUMBER,page.getPageNumber());
				
				jsonObject.put(Constants.Page.PAGE_SIZE,page.getPageSize());
				
				jsonObject.put(Constants.Page.TOTAL_COUNT,page.getTotalCount());
				
				jsonObject.put(Constants.Page.TOTAL_PAGE,page.getPages());
							
			}else{
				jsonObject.put(ErrorMsg.KEY_CODE, 2);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"没有查询到相关数据！");
				
				jsonObject.put(Constants.Page.PAGE_NUMBER,"1");
				
				jsonObject.put(Constants.Page.PAGE_SIZE,"10");
				
				jsonObject.put(Constants.Page.TOTAL_COUNT,"1");
				
				jsonObject.put(Constants.Page.TOTAL_PAGE,"1");
				
			}
			jsonObject.put("memberSize", memberList.size());
			jsonObject.put("pushMessageList", jsonArray);
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
		
		
	}
	
	/**
	 * 商家向会员推送消息(向商家所有会员推送消息)
	 * @return
	 */
	public String pushMessageToUser(){
		JSONObject jsonObject=new JSONObject();
		try {
//			JSONArray jsonArray=new JSONArray();
//			HashMap<String, Object> hashMap;
			
			String shopId=this.getSessionUser().getShopId();
			int successNum=0;
			
			String title=request.getParameter("title");
			
			boolean exists=this.pushMessageService.exists(title,shopId);
			if(!exists){
				String content=request.getParameter("content");
				String sign=request.getParameter("sign");
				String message="";
				if(!sign.equals("")){
					message="【"+sign.trim()+"】";
				}
				message+=content.trim();
				
				//获取商家所有会员的userID
				Map queryMap=new HashMap();
				queryMap.put(McMember.COL_SHOP_ID, shopId);
				SqlUtis.prepareSql(queryMap, SqlUtis.getSQLRequired(queryMap,McMember.COL_SHOP_ID,Types.VARCHAR,SqlUtis.EQ));
				//获取会员列表
				List<McMember> memberList=this.mcMemberService.list(queryMap);
				String type="2";//消息类型(1订单通知，2商家推送消息通知)
				if(memberList!=null){
					for (int i = 0; i < memberList.size(); i++) {
						boolean success=this.sendMessageService.pushMessageToUserByShop(memberList.get(i).getUserId(), message,type,title,shopId);
						if(success){
							successNum++;
						}
					}
					
						jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_OK);
						jsonObject.put(ErrorMsg.KEY_MESSAGE,"调用成功");
				}else{
					jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
					jsonObject.put(ErrorMsg.KEY_MESSAGE,"您的会员人数为零，发送失败！");
					
				}
			}else{
				jsonObject.put(ErrorMsg.KEY_CODE, ErrorMsg.CALL_FAIL);
				jsonObject.put(ErrorMsg.KEY_MESSAGE,"推送消息的标题重复，请重新输入！");
			}
			
			
			
			
			
			
			
		} catch (BusinessException e) {
			jsonObject = JSONObject.fromObject(e.getErrorMsg());
		} catch (Exception e) {
			jsonObject = JSONObject.fromObject(new ErrorMsg(e.getMessage()));
			e.printStackTrace();
		}
		return this.writeJson(jsonObject);
	}
	
	
	
}
